// src/services/scholarsDashboardService/tableSearchScholars.ts

import { BASE_URL } from '@/services/apiConfig';
import type { ScholarRecord } from '@/services/scholarsDashboardService/tableScholarRecords';

interface ScholarSearchParams {
  skip?: number;
  limit?: number;
  keywords?: string;
  start_date_input?: string;
  end_date_input?: string;
}

interface ScholarSearchResponse {
  total: number;
  scholars: ScholarRecord[];
}

// Helper function to validate date format (YYYY-MM-DD)
const isValidDateFormat = (dateStr: string): boolean => {
  const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
  if (!dateRegex.test(dateStr)) return false;

  const date = new Date(dateStr);
  return !isNaN(date.getTime()) && date.toISOString().slice(0, 10) === dateStr;
};

const searchScholars = async (
  params: ScholarSearchParams = {}
): Promise<ScholarSearchResponse> => {
  const token = localStorage.getItem('token');
  if (!token) throw new Error('No token found');

  // Validate date formats if provided
  if (params.start_date_input && !isValidDateFormat(params.start_date_input)) {
    throw new Error('start_date_input must be in YYYY-MM-DD format');
  }
  if (params.end_date_input && !isValidDateFormat(params.end_date_input)) {
    throw new Error('end_date_input must be in YYYY-MM-DD format');
  }

  const query = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== '') {
      query.append(key, String(value));
    }
  });

  const res = await fetch(`${BASE_URL}/scholars/full/search?${query.toString()}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!res.ok) {
    const err = await res.text();
    throw new Error(`Fetch failed: ${res.status} - ${err}`);
  }

  const data = await res.json();
  return data;
};

export { searchScholars };